package com.wry.service.impl;

import com.wry.dto.AccountDeductedDTO;
import com.wry.entity.TAccount;
import com.wry.service.AccountApiService;
import com.wry.service.TAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * <h1>  <h1>
 *
 * @author 魏如元
 * @since 2022/10/10
 */
@Service
@Slf4j
public class AccountApiServiceImpl implements AccountApiService {

    @Resource
    private TAccountService tAccountService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void accountDeducted(AccountDeductedDTO deductedDTO) {
        final TAccount tAccount = tAccountService.lambdaQuery()
                .eq(TAccount::getUserId, deductedDTO.getUserId())
                .one();
        if (Objects.isNull(tAccount)){
            log.warn("userId = {} is null", deductedDTO.getUserId());
            return;
        }

        // 可用额度减
        BigDecimal residue = tAccount.getResidue().subtract(deductedDTO.getMoney());
        // 已用额度加
        BigDecimal used = tAccount.getUsed().add(deductedDTO.getMoney());

        tAccountService.lambdaUpdate()
                .set(TAccount::getResidue, residue)
                .set(TAccount::getUsed, used)
                .update(tAccount);
    }
}
